package org.zhxy.core.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.zhxy.common.config.MapperFactory;
import org.zhxy.common.config.ServerFactory;
import org.zhxy.common.response.Result;
import org.zhxy.common.utils.Constants;
import org.zhxy.common.utils.UploadUtils;
import org.zhxy.entity.system.User;
import org.zhxy.entity.system.UserMaterial;

import java.io.IOException;
import java.util.Date;
import java.util.List;


@Service
@Transactional
public class UserService {


    //TODO:可以把用户的所有信息查询出来
    public User findByUsername(String username) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq(Constants.Parameters.USERNAME,username);
        return MapperFactory.userMapper.selectOne(userQueryWrapper);
    }

    public Result updateStatusForUser(User user) {
        MapperFactory.userMapper.updateStatusForUser(user.getId(),user.getStatus());

        return Result.SUCCESS();
    }

    public Result uploadImage(MultipartFile file, String id) throws IOException {
        String uploadFile = UploadUtils.createUploadFile(ServerFactory.fastFileStorageClient, file);
        String url = Constants.SERVER.FAST_DFS_SERVER_URL + uploadFile;
        UserMaterial userMaterial = UserMaterial.builder()
                .name(file.getOriginalFilename()).userId(id).materialImage(url).createTime(new Date()).build();
        MapperFactory.userMaterialMapper.insert(userMaterial);
        return Result.SUCCESS();
    }

    public List<UserMaterial> getUserImageList(String userId) {
        QueryWrapper<UserMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.DB.COLUMN_USER_ID,userId);
        queryWrapper.orderByDesc(Constants.DB.CREATE_TIME);
        return MapperFactory.userMaterialMapper.selectList(queryWrapper);
    }

    public Result removeUserImage(String id) {
        MapperFactory.userMaterialMapper.deleteById(id);
        return Result.SUCCESS();
    }
}
